import React from 'react';
import BaseComp from '../Base/BaseComp';
import TableComp from '../TableComp';
import { Button, Input, Space, Tooltip } from 'antd';
import { forEach, isArray, isBoolean, isEmpty, isFunction, isNumber, isObject, map, omit, pick } from 'lodash-es';
import styles from './index.module.less';
import PropTypes from 'prop-types';
import { getCompByType } from '../Base/helper/getCompByType';
import { getRandomKey, recursiveMap, QueryFilter } from 'jh-utils';
import { ComponentType, FieldCtrl, TableBarActions } from '../Config';
import AbstractEditDataGrid from '../Base/AbstractEditDataGrid';
import FinderSelect from '../FinderSelect';

const { Search } = Input;

function buildFilterNotIn(keyFieldPrimaryKey, data, fieldName) {
    if ('id' === keyFieldPrimaryKey) {
        return buildFilterNotInId(data, fieldName);
    } else {
        return buildFilterNotInCode(data, fieldName);
    }
}

/**
 * 根据 data 构建 "id not in" 过滤条件
 */
function buildFilterNotInId(data, fieldName) {
    let hql = '(-1';

    forEach(data, item => {
        if (item && item[fieldName]) {
            hql += ',' + item[fieldName].id;
        }
    });
    hql += ')';
    if (hql === '(-1)') return false;
    return QueryFilter.buildByValue('id', QueryFilter.AND, QueryFilter.NOT_IN, hql);
}

/**
 * 根据 data 构建 "code not in" 过滤条件
 */
function buildFilterNotInCode(data, fieldName) {
    let hql = '(\'\'';
    forEach(data, item => {
        if (item && item[fieldName]) {
            hql += ',\'' + item[fieldName].code + '\'';
        }
    });
    hql += ')';
    if (hql === '(\'\')') return false;
    return QueryFilter.buildByValue('code', QueryFilter.AND, QueryFilter.NOT_IN, hql);
}

export default class DetailTable extends AbstractEditDataGrid {

    static defaultProps = {
        actionBar: true, // 是否需要操作栏
        isBatchAddUniq: true, // “批量添加行”操作，是否需要过滤已选的数据
    };

    /**
     * @type {TableComp}
     */
    tableRef;

    /**
     * @type {ActionBar}
     */
    barRef;

    componentDidMount() {
        super.componentDidMount && super.componentDidMount();
        // 将本组件的实例存到 appins 的 dtIns 变量中，用于被 appins 在必要时调用
        const { appins, fieldName, customprops } = this.props;
        if (appins && isFunction(appins.setFieldInsByName) && !isEmpty(fieldName)) {
            appins.setFieldInsByName(fieldName, this, customprops);
        }
    }

    /**
     * 获取表格数据
     * @param onlyChange {boolean} 是否只获取改变了的数据。默认 true
     * @return {undefined|{comboVal, compVal}|[]}
     */
    getAjaxData(onlyChange = true) {

        if (this.tableRef && isFunction(this.tableRef.getAjaxData)) {
            return this.tableRef.getAjaxData(onlyChange);
        }
    }

    /**
     * 获取不为空的数据
     * @param onlyChange {boolean} 是否只获取改变了的数据。默认 false
     * @return {*[]}
     */
    getDataNoEmpty(onlyChange = true) {

        if (this.tableRef && isFunction(this.tableRef.getDataNoEmpty)) {
            return this.tableRef.getDataNoEmpty(onlyChange);
        }
    }


    /**
     * 获取删除了的记录
     * @param fullRecord {boolean} 是否需要返回完整的记录。默认 false，只返回删除了的 id 数组
     * @return {[]}
     */
    getDeleted(fullRecord = false) {

        if (this.tableRef && isFunction(this.tableRef.getDeleted)) {
            return this.tableRef.getDeleted(fullRecord);
        }
    }

    /**
     * 获取选中的记录
     * @param fullRecord {boolean} 是否需要返回完整的记录。默认 true。否则只返回的 id 数组
     * @return {[]}
     */
    getSelected(fullRecord = true) {

        if (this.tableRef && isFunction(this.tableRef.getSelected)) {
            return this.tableRef.getSelected(fullRecord);
        }
    }

    /**
     * 表格是否有变化
     * @return {boolean}
     */
    hadChanged() {

        if (this.tableRef && isFunction(this.tableRef.hadChanged)) {
            return this.tableRef.hadChanged();
        }
    }

    /**
     * 设置表格数据
     * @param data
     * @param afterCb
     * @param reMountTable {boolean} 是否需要重载 Table。默认 false
     * @param isInit {boolean} 是否初始化，如果是，则添加 defaultRowCnt 相关逻辑
     */
    setData(data, afterCb, reMountTable = false, isInit = false) {

        if (this.tableRef && isFunction(this.tableRef.setData)) {
            return this.tableRef.setData(data, afterCb, reMountTable, isInit);
        }
    }

    /**
     * 更新某条记录的值。可指定更新哪些字段
     * @param record
     * @param updateFields {[string]} 需要更新的字段数组。如果为空，则更新 record 的所有字段
     * @param afterCb
     */
    updateRecordFields(record, updateFields = [], afterCb = null) {
        if (this.tableRef && this.tableRef.tableRef && isFunction(this.tableRef.tableRef.updateRecordFields)) {
            this.tableRef.tableRef.updateRecordFields(record, updateFields, afterCb);
        }
    }

    /**
     * 设置表格的操作权限
     * @param viewConfig {{
     *     body: {
              "fieldName": string,
              "addable": boolean,
              "deletable": boolean,
              "editable": boolean,
              "standard": boolean
            },
            fields: [{
              "fieldName": string,
              "control": number
            }]
     * }}
     * body 的结构：{
              "fieldName": "securityGroups",
              "addable": false, // 是否可添加
              "deletable": false, // 是否可删除
              "editable": false, // 是否可编辑
              "standard": false // 是否标准表体
            }
     * fields 的结构：[{
              "fieldName": "roles.corp", // 字段名
              "control": 2 // 对应 Config/FieldCtrl
            }]
     * @param afterCb
     */
    setViewConfig(viewConfig, afterCb) {

        if (!isEmpty(viewConfig)) {
            const { body, fields } = viewConfig;
            // 设置表头操作栏
            if (body && this.barRef && this.barRef.setEnabledByBody) {
                this.barRef.setEnabledByBody(body);
            }
            // 设置表体字段的权限
            this.setFieldCtrlByFields(fields, false);
            this.setState({ randomKey: getRandomKey(), body }, afterCb);
            return;
        }
        afterCb && afterCb();

    }

    /**
     * 设置头部按钮是否可用。（强制设置，权重最大）
     * @param actions {string[]}
     * @param enabled {boolean}
     * @param afterCb
     */
    setActionEnabled(actions, enabled, afterCb = null) {
        if (this.barRef && this.barRef.setActionEnabled) {
            this.barRef.setActionEnabled(actions, enabled, afterCb);
        }
    }

    /**
     * 设置头部按钮是否可用。（组件内控制，权重最小）
     * @param actions {string[]}
     * @param enabled {boolean}
     * @param afterCb
     */
    setActionEnabledDef(actions, enabled, afterCb = null) {
        // 控制“头部操作栏”的按钮可用状态
        if (this.barRef && this.barRef.setActionEnabledDef) {
            this.barRef.setActionEnabledDef(actions, enabled, afterCb);
        }
    }

    /**
     * 设置“列渲染”
     * @param fieldName {string}
     * @param render {function(value, record, rowIndex)}
     */
    setColRender(fieldName, render) {

        if (this.tableRef && isFunction(this.tableRef.setColRender)) {
            return this.tableRef.setColRender(fieldName, render);
        }
    }

    // “批量添加行”的查找器-编辑前 的回调
    batchAddEditBeforeCbs = [];
    // “批量添加行”的查找器-编辑后 的回调
    batchAddEditAfterCbs = [];

    /**
     * 设置“批量添加行”的查找器-编辑前 的回调
     * @param func
     */
    addBatchAddEditBefore(func) {
        this.batchAddEditBeforeCbs.push(func);
    }

    /**
     * 设置“批量添加行”的查找器-编辑后 的回调
     * @param func
     */
    addBatchAddEditAfter(func) {
        this.batchAddEditAfterCbs.push(func);
    }

    /**
     * 操作栏按钮-被点击之后
     * @param e
     * @param actKey
     */
    hdlClickBar(e, actKey) {
        console.log('hdlClickBar(actKey)', actKey);
        // “批量添加”
        if (TableBarActions.batchAdd === actKey) {
            if (this.batchFinder && this.batchFinder.compIns) {
                // 清空查找器数据
                this.batchFinder.setValue && this.batchFinder.setValue(null);
                // 显示查找器弹框
                this.batchFinder.compIns.hdlClickMenu && this.batchFinder.compIns.hdlClickMenu();
            }


        } else {
            this.editRow(actKey);
        }
    }

    /**
     * 搜索表格内容
     * @param search {string} 输入框的内容
     */
    hdlSearchTb(search) {
        if (this.tableRef && this.tableRef.tableRef && this.tableRef.tableRef.searchInTable) {
            this.tableRef.tableRef.searchInTable(search);
        }
    }

    mainRender() {
        const disabled = this.getPropsByName('disabled');
        const { onRef, colsConf, columns, actionBar, ...restProps } = this.getProps();
        const tableMoreProps = restProps;

        if (!isEmpty(this.state.body)) {
            tableMoreProps.actionConf = this.state.body;
        }

        let keyField = tableMoreProps.actionConf && tableMoreProps.actionConf.keyField; // 此明细表的关键字段
        let keyFieldPrimaryKey = 'id';
        let keyFieldCompProps = {};
        let canBatchAdd = false; // 是否可以“批量添加”，只有当“关键字段”是查找器类型时才能“批量添加”

        const fieldCtrlObj = this.fieldCtrlObj;
        const fieldEnabledObj = this.fieldEnabledObj;
        let belong = {
            customprops: this.props.customprops,
            body: !isEmpty(this.props.fieldName),
            bodyFieldName: this.props.fieldName,
            ...(tableMoreProps.belong || {}),
        };

        let isConfCol = isArray(colsConf);
        let factCols = (isConfCol ? colsConf : columns) || [];

        const cols = recursiveMap(factCols, (col) => {
            const dataIndex = col.dataIndex || col.name;

            // 如果是“关键字段”列，且是查找器类型，则取出关键字段的 finderCode 和 appCode
            if (keyField && dataIndex === keyField && col.componentType === ComponentType.FINDER) {
                keyFieldCompProps.finderCode = col.finderCode;
                keyFieldCompProps.appCode = col.appCode;
                keyFieldPrimaryKey = 'com.jianhui.persistence.domain.RelationalObject' === col.dataType ? 'code' : 'id';
                canBatchAdd = true;
            }

            if (disabled) {
                return { ...col, editable: false };
            }
            const fieldCtrl = fieldCtrlObj[dataIndex] !== undefined ? fieldCtrlObj[dataIndex] : col.fieldCtrl;
            const fieldEnabled = fieldEnabledObj[dataIndex];
            const reCol = { ...col, fieldCtrl: fieldCtrl };
            // 如果是传 colsConf 属性进来的，且没设置 editable 属性，且此列不是只读或隐藏，则列都可编辑
            let editable = !!(isConfCol && 'undefined' === typeof reCol.editable && reCol.componentType);

            if (isBoolean(fieldEnabled)) {

                if (false === fieldEnabled) editable = false;

            } else if ('undefined' !== typeof fieldCtrl && null !== fieldCtrl && (
                fieldCtrl === FieldCtrl.READONLY || fieldCtrl === FieldCtrl.HIDDEN
            )) {
                editable = false;
            }

            if (editable) {
                const moreCompProps = { // compProps 会设置到"单元格编辑时"组件的属性
                    autoFocus: true,
                    defaultOpen: true,
                    appins: this.props.appins,
                    belong: {
                        ...belong,
                        cellFieldName: dataIndex,
                    },
                    colsConf: factCols,
                    fieldCtrl: fieldCtrl,
                    format: col.format,
                    floatNum: col.floatNum,
                };
                const { selector, finderCode, appCode, compProps, referenceAppInfo, plural, custEmbed } = reCol;
                if (selector) moreCompProps.selector = selector;
                if (finderCode) moreCompProps.finderCode = finderCode;
                if (plural) { // 查找器多态
                    moreCompProps.plural = plural;
                    moreCompProps.referenceAppInfo = referenceAppInfo;
                }
                if (appCode) moreCompProps.appCode = appCode;
                if (custEmbed) moreCompProps.custEmbed = custEmbed;
                if (!isEmpty(compProps)) moreCompProps.compProps = compProps;

                // 设置“单元格-编辑前”的回调
                if (this.editBeforeCbs[dataIndex]) {
                    moreCompProps.compProps = {
                        ...(moreCompProps.compProps || {}),
                        exeInMount: (compIns) => {
                            compIns.editBeforeCbs = this.editBeforeCbs[dataIndex];

                            if (compProps && compProps.exeInMount) {
                                compProps.exeInMount(compIns);
                            }
                        },
                    };
                }

                reCol.editable = true;
                reCol.editingSetting = (value, record, rowIndex, moreProps = {}) => {
                    return {
                        options: { // options 会设置到 Form.Item 的属性
                        },
                        comp: getCompByType(reCol.componentType, {
                            ...moreCompProps,
                            rowIndex,
                            ...moreProps,
                        }),
                    };
                };
            }
            return reCol;
        });

        let compHeight = tableMoreProps.style && tableMoreProps.style.height ? tableMoreProps.style.height : '400px';
        let tHeight = actionBar ? 'calc(100% - 40px)' : '100%';

        // console.log('DetailTable render', keyField, keyFieldCompProps, canBatchAdd);
        const rowSelection = {
            /* 选择框的默认属性配置 */
            getCheckboxProps: () => ({ disabled }),
            /* 左侧 checkbox 选中项发生变化时的回调*/
            onChange: (selectedRowKeys, selectedRows, ...args) => {
                // 控制“头部操作栏”的按钮可用状态
                // 如果勾选行，则“删除、复制、剪切”可用
                this.setActionEnabledDef([
                    TableBarActions.delete, TableBarActions.cut, TableBarActions.copy,
                ], !isEmpty(selectedRowKeys));

                // 执行 props.rowSelection 的回调
                const rowSelection = this.getPropsByName('rowSelection');
                if (rowSelection && rowSelection.onChange) {
                    rowSelection.onChange(selectedRowKeys, selectedRows, ...args);
                }
            },
        };
        const selectObj = this.getPropsByName('rowSelection');
        if (selectObj && selectObj.needSelectedKeys === true) {
            rowSelection.selectedRowKeys = selectObj.selectedRowKeys || [];
        }

        return (
            <div style={{ ...pick(tableMoreProps.style, ['width']), height: compHeight, position: 'relative' }}>
                {
                    actionBar && (
                        <ActionBar
                            disabled={disabled}
                            isShowSearch={this.props.isShowSearch}
                            actionsBtn={this.props.actionsBtn}
                            canBatchAdd={canBatchAdd}
                            onRef={(ref) => {
                                this.barRef = ref;
                            }}
                            onClick={this.hdlClickBar.bind(this)}
                            onSearch={this.hdlSearchTb.bind(this)}
                        />
                    )
                }
                <TableComp
                    fieldEnabledObj={fieldEnabledObj}
                    needNO={true}
                    rowSelect={true}
                    canSort={true}
                    autoAdd={true}
                    bordered={true}
                    {...tableMoreProps}
                    pagination={{
                        style: {
                            margin: '5px 0px',
                            height: 24,
                        },
                        pageSize: 100,
                        position: ['bottomRight'],
                        // simple: true,
                        showLessItems: true,
                        size: 'small',
                        hideOnSinglePage: true,
                        ...(tableMoreProps.pagination || {}),
                    }}
                    belong={belong}
                    columns={cols}
                    rowSelection={rowSelection}
                    onCellUpdate={(dataIndex, newRecord, prevChangedRecord, ...args) => {
                        // console.log('onCellUpdate ' + dataIndex, newRecord);
                        let reVal;
                        // 执行“单元格-编辑后”的回调
                        const editAfterCbs = this.editAfterCbs[dataIndex];
                        forEach(editAfterCbs, (cb) => {
                            if (isFunction(cb)) {
                                reVal = cb(newRecord[dataIndex], newRecord, dataIndex, belong.bodyFieldName, prevChangedRecord);
                                if (false === reVal) return false;

                                if (isObject(reVal) && !isEmpty(reVal)) newRecord = reVal;
                            }
                        });
                        if (false === reVal) return false;

                        const func = this.getPropsByName('onCellUpdate');

                        if (isFunction(func)) {
                            return func(dataIndex, newRecord, prevChangedRecord, ...args);
                        }
                        return reVal;
                    }}
                    onRowUpdate={(arg) => {
                        let reVal;

                        // 执行“行操作”的回调
                        if (isFunction(this.rowActionCb)) {
                            reVal = this.rowActionCb(arg);
                            if (false === reVal) return false;
                        }
                        // 根据权限判断是否允许“增、删等行”操作
                        // if (this.barRef && !this.barRef.getEnabledByAction(arg.type, false)) {
                        //     return false;
                        // }

                        const func = this.getPropsByName('onRowUpdate');

                        if (isFunction(func)) {
                            return func(arg);
                        }
                        return reVal;
                    }}
                    getDefaultRecord={(record) => {
                        return this.runPropsFunc('getDefaultRecord')(record, {}, this);
                    }}
                    style={{ ...omit(tableMoreProps.style, ['width', 'height']), height: tHeight }}
                    onRef={(ref) => {
                        this.tableRef = ref;
                    }}
                />
                {
                    canBatchAdd && (
                        <div style={{ display: 'none' }}>
                            <FinderSelect
                                appins={restProps.appins}
                                multi={true}
                                onRef={(ins) => {
                                    this.batchFinder = ins;

                                    // 编辑前
                                    if (isFunction(ins.addEditBeforeHandler)) {
                                        ins.addEditBeforeHandler((compIns) => {
                                            // 如果需要过滤“已选数据”，则添加相关过滤条件
                                            let { isBatchAddUniq } = this.getProps();
                                            if (isBatchAddUniq) {
                                                const tmpList = this.getData(false);
                                                compIns.filter = buildFilterNotIn(keyFieldPrimaryKey, tmpList, keyField);
                                            }
                                            console.log('forEach batchAddEditBeforeCbs', compIns.filter, this.batchAddEditBeforeCbs);
                                            forEach(this.batchAddEditBeforeCbs, (cb) => {
                                                cb(compIns);
                                            });
                                        });
                                    }
                                    // 编辑后
                                    if (isFunction(ins.addEditAfterHandler)) {
                                        ins.addEditAfterHandler((value) => {
                                            // console.log('addEditAfterHandler value', value);
                                            // 批量添加行到表格
                                            if (!isEmpty(value) && isArray(value)) {
                                                const tmpList = this.getData(false);

                                                forEach(value, item => {
                                                    if (!isEmpty(item)) {
                                                        tmpList.unshift({
                                                            key: getRandomKey(),
                                                            [keyField]: item,
                                                        });
                                                    }
                                                });
                                                // console.log('addEditAfterHandler tmpList', tmpList);
                                                this.setData(tmpList);
                                            }

                                            // console.log('forEach batchAddEditAfterCbs', this.batchAddEditAfterCbs);
                                            forEach(this.batchAddEditAfterCbs, (cb) => {
                                                cb(value);
                                            });
                                        });
                                    }
                                }}
                                {...keyFieldCompProps}
                            />
                        </div>
                    )
                }
            </div>
        );
    }
}

const actions = [
    // { en: TableBarActions.add, cn: '添行', icon: require('../../assets/svg/add.svg') },
    // { en: TableBarActions.insert, cn: '插行', icon: require('../../assets/svg/insert.svg') },
    // { en: TableBarActions.batchAdd, cn: '批量添加行', icon: require('../../assets/svg/batchAdd.svg') },
    // { en: TableBarActions.delete, cn: '删除', icon: require('../../assets/svg/delete.svg') },
    // {en: 'copy', cn: '复制', icon: require('../../assets/svg/copy.svg')},
    // {en: 'cut', cn: '剪切', icon: require('../../assets/svg/cut.svg')},
    // {en: 'paste', cn: '粘贴', icon: require('../../assets/svg/paste.svg')},
    // { en: TableBarActions.down, cn: '下移', icon: require('../../assets/svg/down.svg') },
    // { en: TableBarActions.up, cn: '上移', icon: require('../../assets/svg/up.svg') },
    // { en: TableBarActions.sort, cn: '刷新排序', icon: require('../../assets/svg/sorting.svg') },
];

const getActionKeys = (enabled = true, excepts = []) => {
    const arr = {};
    forEach(actions, (act) => {
        if (-1 === excepts.indexOf(act.en)) {
            arr[act.en] = enabled;
        }
    });
    return arr;
};

class ActionBar extends BaseComp {

    static propTypes = {
        onClick: PropTypes.func,
        onSearch: PropTypes.func,
        disabled: PropTypes.bool,
        isShowSearch: PropTypes.bool,
        canBatchAdd: PropTypes.bool,
        actionsBtn: PropTypes.arrayOf(PropTypes.string),
    };

    /**
     * 操作“是否可用”权限设置
     * @type {{}}
     */
    enabledAuth = {};

    /**
     * 操作“是否可用”强制设置。权重第二，仅次于 props.disabled
     * @type {{}}
     */
    enabledForce = {};

    /**
     * 操作“是否可用”组件内设置。权重最小
     * @type {{}}
     */
    enabledActions = {};

    constructor(props) {
        super(props);
        this.resetDef();
    }

    resetDef() {
        this.enabledActions = {};
        this.enabledActions[TableBarActions.delete] = false;
    }

    /**
     * 设置按钮的操作权限。（权限控制，是否可用的基础显示）
     * @param body {{
              "fieldName": string,
              "addable": boolean,
              "deletable": boolean,
              "editable": boolean,
              "standard": boolean
            }}
     * body 的结构举例：{
              "fieldName": "fieldNameX", // "DetailTable 作为详情页字段使用时"的字段名
              "addable": false, // 是否可添加
              "deletable": false, // 是否可删除
              "editable": false, // 是否可编辑
              "standard": false // 是否标准表体
            }
     * @param afterCb
     */
    setEnabledByBody(body, afterCb) {

        if (body) {
            const canBatchAdd = this.getPropsByName('canBatchAdd');
            const { addable, deletable, editable } = body;
            const copyable = true; // copyable 字段后端没返回，默认是 true
            // 是否可复制 = editable &&  copyable
            // 是否可剪切 = deletable && copyable &&  editable
            // 是否可粘贴 = copyable && addable && editable
            this.enabledAuth = {
                add: true === addable,
                insert: true === addable,
                batchAdd: true === addable && canBatchAdd,
                delete: true === deletable,
                copy: true === editable && copyable,
                cut: true === deletable && copyable && editable,
                paste: true === copyable && addable && editable,
                down: true === editable,
                up: true === editable,
                sort: true === editable,
            };
            this.setState({ randomKey: getRandomKey() }, afterCb);
            return;
        }
        afterCb && afterCb();
    }

    /**
     * 设置按钮是否可用。（强制设置，权重第二，仅次于 props.disabled）
     * @param actions {string[]}
     * @param enabled
     * @param afterCb
     */
    setActionEnabled(actions, enabled, afterCb) {
        if (isEmpty(actions)) {
            this.enabledForce = getActionKeys(enabled);
        } else {
            forEach(actions, (act) => {
                if (act) {
                    this.enabledForce[act] = enabled;
                }
            });
        }
        this.setState({ randomKey: getRandomKey() }, afterCb);
    }

    /**
     * 设置按钮是否可用。（组件内控制，权重最小）
     * @param actions {string[]}
     * @param enabled
     * @param afterCb
     */
    setActionEnabledDef(actions, enabled, afterCb) {

        if (isEmpty(actions)) {
            this.enabledActions = getActionKeys(enabled);
        } else {
            forEach(actions, (act) => {
                if (act) {
                    this.enabledActions[act] = enabled;
                }
            });
        }
        this.setState({ randomKey: getRandomKey() }, afterCb);
    }

    /**
     * 获取按钮是否可用
     * @param actionKey {string}    操作按钮的标识，对应 TableBarActions
     * @param withDefault {boolean} 是否需要加上“组件内的控制”。默认 true。
     *                                  false：只从权限判断是否操作
     */
    getEnabledByAction(actionKey, withDefault = true) {
        // disabled 控制，权重最大
        if (this.props.disabled) return false;

        // 如果是“批量添加”，则取“添加”的权限+props.canBatchAdd 作为判断依据
        if (actionKey === TableBarActions.batchAdd) {
            return this.getEnabledByAction(TableBarActions.add) && this.getPropsByName('canBatchAdd');
        }

        // 强制控制
        if (isBoolean(this.enabledForce[actionKey])) return this.enabledForce[actionKey];
        // 权限控制“不可操作”
        if (false === this.enabledAuth[actionKey]) return false;
        if (withDefault) {
            // 普通控制
            return false !== this.enabledActions[actionKey];
        } else {
            return true;
        }
    }


    render() {
        const { isShowSearch = true, actionsBtn = [] } = this.props;
        //自定义选择表头按钮
        let newActions = [];

        if (!isEmpty(actionsBtn)) {
            forEach(actionsBtn, acb => {
                forEach(actions, act => {
                    let newActs = { ...act };
                    if (act.en === acb) {
                        newActions.push(newActs);
                    }
                });
            });
        } else {
            newActions = [...actions];
        }

        return (
            <div className={styles.bar}>
                {
                    map(newActions, (action) => (
                        <ActionBtn
                            key={action.en}
                            src={action.icon}
                            alt={this.formatMsgByCn(action.cn)}
                            onClick={(e) => {
                                this.props.onClick && this.props.onClick(e, action.en);
                            }}
                            disabled={!this.getEnabledByAction(action.en)}
                        />
                    ))
                }

                {
                    isShowSearch && <Search key={'search'}
                                            placeholder={this.formatMsgByCn('请输入')}
                                            onSearch={this.props.onSearch}
                                            style={{ width: 200, marginLeft: 8 }}
                                            size={'small'}
                    />
                }
            </div>
        );
    }
}

const ActionBtn = (props) => {
    const { src, alt, onClick, ...restProps } = props;

    const btnComp = (
        <Button className={styles.antBtn}
                type="link"
                size={'small'}
                onClick={onClick}
                {...restProps}>
            <img src={src} alt={alt}/>
        </Button>
    );

    if (restProps.disabled) {
        return btnComp;
    }

    return (
        <Tooltip placement={'bottom'} title={alt} overlayStyle={{ fontSize: 12 }}>
            {btnComp}
        </Tooltip>
    );
};